#include <QUdpSocket>
#include <QDebug>
#include <QTimer>
#include "agenttasktimer.h"
#include "macro.h"
#include "Agent/agentprotocol.h"

AgentTaskTimer::AgentTaskTimer(QMap <QByteArray,QByteArray> mapIPPortReqPacket,QByteArray packet,
     QString paramAppIP, quint16 paramAppPort, QObject *parent)
    :AgentTaskBase(mapIPPortReqPacket,packet,paramAppIP,paramAppPort,parent)
{


}
void AgentTaskTimer::slotInitDerivedClass()
{
    if(fieldIsSingleShot)
    {
        QTimer::singleShot(fieldTimeOutSeconds*1000,this,SLOT(slotTimerSendPacketToServer()));

    }
    else
    {
        timer=new QTimer(this);
        timer->start(fieldTimeOutSeconds*1000);
        connect(timer,SIGNAL(timeout()),this,SLOT(slotTimerSendPacketToServer()));
    }

    isCreatedSuccessfully=true;

}

void AgentTaskTimer::analyzeIncomeDatagram(QByteArray packet)
{
    QByteArray packetUpper=packet.simplified().toUpper();

    if(packetUpper.startsWith("ERR"))
    {
        emit sigSendDataToApp(agentProtocol->replyLineBadRequest()+"\n\n"+
            packet,appIP,appPort);
        deleteLater();
        return;
    }
    emit sigSendDataToApp(packet,appIP,appPort);
}

void AgentTaskTimer::slotTimerSendPacketToServer()
{
    emit sigSetIPAnalyzeIncomeDatagram(fieldPayLoad,QHostAddress(appIP),appPort);

    if(fieldIsSingleShot)
    {
        QTimer::singleShot(5000,this,SLOT(deleteLater()));
        return;
    }
}

AgentTaskTimer::~AgentTaskTimer()
{
}
